<template>
  <div class="container">
    <div class="head">
      <!-- 增加按钮 -->
      <el-button
        class="add"
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="dialogFormVisible = true"
        >增加</el-button
      >
      <!-- 搜索框 -->
      <el-input
        placeholder="请输入查询内容"
        v-model="searchInput"
        clearable
        style="width: 200px"
      >
      </el-input>
      <!-- 增加商品 -->
      <el-dialog title="增加商品" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="商品名" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="类型" :label-width="formLabelWidth">
            <el-input v-model="form.type" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="单价" :label-width="formLabelWidth">
            <el-input v-model="form.price" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="重量" :label-width="formLabelWidth">
            <el-input v-model="form.weight" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="生产日期" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="保质期" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.livedate"
              type="date"
              placeholder="日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="介绍" :label-width="formLabelWidth">
            <el-input
              v-model="form.describe"
              autocomplete="off"
              type="textarea"
            ></el-input>
          </el-form-item>
          <el-upload
            multiple
            class="avatar-uploader"
            action="http://localhost:3002/uploadFile"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="`http://localhost:3002/images/${imageUrl}`"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img :src="imageUrl" alt="" width="200px" />
          </el-dialog>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible = false">
            <div @click="addhandel">确 定</div>
          </el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <el-table
      :data="
        commodityArr
          .filter(
            (data) =>
              !this.searchInput ||
              data.name
                .toLowerCase()
                .includes(this.searchInput.toLowerCase()) ||
              data.type
                .toLowerCase()
                .includes(this.searchInput.toLowerCase()) ||
              data.price
                .toLowerCase()
                .includes(this.searchInput.toLowerCase()) ||
              data.weight.toLowerCase().includes(this.searchInput.toLowerCase())
          )
          .slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      border
      style="width: 100%"
    >
      <el-table-column fixed prop="name" label="商品名"> </el-table-column>
      <el-table-column prop="type" label="类型"> </el-table-column>
      <el-table-column prop="price" label="单价"> </el-table-column>
      <el-table-column prop="weight" label="重量"> </el-table-column>
      <el-table-column prop="date" label="生产日期"> </el-table-column>
      <el-table-column prop="livedate" label="保质期"> </el-table-column>
      <el-table-column prop="describe" label="介绍"> </el-table-column>
      <el-table-column prop="images" label="描述图片" style="display: flex">
        <template slot-scope="scope" class="imagesList">
          <img
            style="width: 50px; height: 50px; display: inline-block"
            v-for="(item, index) in scope.row.images"
            :key="index"
            :src="`http://localhost:3002/images/${item}`"
            alt=""
          />
        </template>
        <template>
          <el-button size="small" type="success">已通过</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150" align="center">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="primary" size="small"
            >修改</el-button
          >
          <el-button size="small" type="danger" @click="deleteHandel(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        background
        @size-change="handelSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[1, 5, 10, 15, 20]"
        :page-size="pageSize"
        layout=" sizes, prev, pager, next, jumper"
        :total="commoditysList.length"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import service from "../../utils/request";
export default {
  data() {
    return {
      commodityArr: [], // 商品
      roleInfo: localStorage.getItem("roleInfo"), // 获取到本地的管理员信息，为了判断当登录的是平台管理员的时候就显示所有门店
      currentPage: 1,
      pageSize: 5,
      dialogFormVisible: false,
      imageUrl: "",
      dialogVisible: false,
      disabled: false,
      searchInput: "",
      adminId: localStorage.getItem("adminId"),
      form: {
        name: "",
        type: "",
        price: "",
        weight: "",
        date: "",
        livedate: "",
        describe: "",
        images: [],
        adminId: localStorage.getItem("adminId"),
      },
      formLabelWidth: "120px",
    };
  },
  computed: {
    commoditysList() {
      return this.$store.getters["commoditys/commoditysgetter"];
    },
  },
  mounted() {
    console.log(localStorage.getItem("roleInfo"), "---------------");
    // 如果是平台管理员就显示所有门店
    // 获取管理员
    if (!this.adminId) {
      this.$store.dispatch("commoditys/commoditysAction").then(() => {
        this.commodityArr = this.commoditysList;
      });
    }
    // 门店管理员只显示对应的门店
    else {
      let oneCommodityArr = this.commoditysList
        .filter((item) => {
          return item.adminId;
        })
        .filter((item) => item.adminId._id == this.adminId);
      this.commodityArr = oneCommodityArr; // 将筛选出的对应的门店赋值给数组
      this.$store.dispatch("commoditys/commoditysAction").then(() => {
        service.get("/commoditys").then((res) => {
          this.commodityArr = res.rows
            .filter((item) => {
              return item.adminId;
            })
            .filter((item) => item.adminId._id == this.adminId);
        });
      });
    }
  },
  methods: {
    handelSizeChange(val) {
      (this.currentPage = 1), (this.pageSize = val);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleClick(scope) {
      this.$router.push({
        path: `./commoditydetail/${scope._id}`,
        query: { scope: scope },
      });
    },
    deleteHandel(scope) {
      this.$store
        .dispatch("commoditys/deletecommoditysAction", scope._id)
        .then(() => {
          service.get("/commoditys").then((res) => {
            this.commodityArr = res.rows
              .filter((item) => {
                return item.adminId;
              })
              .filter((item) => item.adminId._id == this.adminId);
          });
        });
    },
    addhandel() {
      this.$store.dispatch("commoditys/addcommoditysAction", {
        ...this.form,
        images: this.form.images,
      });

      this.$store
        .dispatch("commoditys/addcommoditysAction", {
          ...this.form,
          images: this.imageUrl,
        })
        .then(() => {
          service.get("/commoditys").then((res) => {
            this.commodityArr = res.rows
              .filter((item) => {
                return item.adminId;
              })
              .filter((item) => item.adminId._id == this.adminId);
          });
        });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.saveName;
      this.form.images.push(res.saveName);
    },
    beforeAvatarUpload(file) {
      let types = ["image/jpeg", "image/jpg", "image/png"];
      const isImage = types.includes(file.type);
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isImage) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt10M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isImage && isLt10M;
    },
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
}
.head {
  display: flex;
  align-content: center;
  margin-bottom: 30px;
}
.add {
  margin-right: 20px;
}
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin: 10px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.images {
  width: 50px;
  height: 50px;
}
/* 图片 */
.imagesList {
  display: flex;
}
.imagesList .imgDecs {
  display: inline-block;
  width: 50px;
  height: 50px;
}
/* 分页 */
.container .el-pagination {
  margin: 20px 0;
}
</style>